package com.arcsoft.commonbase.ext

import android.webkit.MimeTypeMap
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.MultipartBody
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.asRequestBody
import okhttp3.RequestBody.Companion.toRequestBody
import java.io.File
import java.net.URLEncoder
import java.util.*
import kotlin.collections.ArrayList




/**
 *文件上传文本
 */
fun requestBodyCreateText(string: String): RequestBody {
    return string.toRequestBody("text/plain".toMediaTypeOrNull())
}

/**
 *文件批量上传
 */
fun filesToMultipartBodyParts(files: List<File>): List<MultipartBody.Part> {
    val parts: MutableList<MultipartBody.Part> = ArrayList(files.size)
    for (file in files) {
        val index = file.name.lastIndexOf(".")
        var type: String? = "image/*"
        if (index != -1) {
            val suffix = file.name.substring(index + 1).toLowerCase(Locale.US)
            type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(suffix)
        }
        val requestFile = file.asRequestBody(type?.toMediaTypeOrNull())
        val part = MultipartBody.Part.createFormData("files", URLEncoder.encode(file.name, "UTF-8"), requestFile)
        parts.add(part)
    }
    return parts
}

fun fileToPart(file: File): MultipartBody.Part {
    val requestFile = file.asRequestBody("multipart/form-data".toMediaTypeOrNull())
    return MultipartBody.Part.createFormData("file", URLEncoder.encode(file.name, "UTF-8"), requestFile)
}